const HTTP = "https://apis.map.qq.com/ws/geocoder/v1/";
//腾讯地图的key
const TXMapKey = "4IJBZ-DLACP-3QBDS-LI4FT-U2MZZ-5KFFA";

export default {
	/**
	 * 定位
	 * @param {Function} callback 回调函数
	 */
	getLocation(callback) {
		// #ifdef MP-WEIXIN
		this.getAuthorize(callback);
		// #endif
		// #ifndef MP-WEIXIN
		this.getCurrentCoordition(callback);
		// #endif
	},
	/**
	 * 获取授权信息
	 */
	getAuthorize(callback) {
		let that = this;
		uni.authorize({
			scope: "scope.userLocation",
			success: (result) => {
				//用户同意授权
				that.getCurrentCoordition(callback);
			},
			fail: () => {
				//用户拒绝授权
				that.openConfirm();
			},
		});
	},
	/**
	 * 当用户第一次拒绝后再次请求授权
	 */
	openConfirm() {
		let that = this;
		uni.showModal({
			title: "请求授权当前位置",
			content: "需要获取您的地理位置，请确认授权",
			success: (result) => {
				if (result.confirm) {
					//打开地图权限设置
					uni.openSetting();
				} else if (result.cancel) {
					uni.showToast({
						title: "你拒绝了授权，无法获取您的位置信息",
						icon: "none",
						duration: 1500,
					});
				}
			},
		});
	},
	/**
	 * 获取当前位置的经纬度
	 */
	getCurrentCoordition(callback) {
		uni.getLocation({
			type: "wgs84",
			success: (res) => {
				console.log("获取到当前位置信息", res);
				// #ifdef MP-WEIXIN
				this.appletGetCurrentAddress(
					res.latitude,
					res.longitude,
					callback
				);
				// #endif

				// #ifndef MP-WEIXIN
				this.getCurrentAddress(res.latitude, res.longitude, callback);
				// #endif
			},
			fail: (err) => {
				console.log("获取位置信息失败", err);
			},
		});
	},
	/**
	 * 获取当前城市信息 小程序
	 */
	appletGetCurrentAddress(lat, lng, callback) {
		let url = `${HTTP}?key=${TXMapKey}&location=${encodeURIComponent(lat)},
		${encodeURIComponent(lng)}&get_poi=0`;
		uni.request({
			url: url,
			data: {},
			header: { "content-type": "application/json" },
			method: "GET",
			dataType: "json",
			responseType: "text",
			success: (result) => {
				console.log("获取到当前城市信息", result);
				let data = result.data.result;
				const address = data.address; //地址
				const province = data.address_component.province; //省
				const city = data.address_component.city; //市
				const district = data.address_component.district; //区
				const street = data.address_component.street; //街道
				const adcode = data.ad_info.adcode; //adcode

				let obj = {
					lat,
					lng,
					address,
					province,
					city,
					district,
					street,
					adcode,
				};
				callback & callback(obj);
			},
			fail: () => {},
			complete: () => {},
		});
	},

	/**
	 * 获取当前城市信息 H5 APP
	 */
	getCurrentAddress(lat, lng, callback) {},
};


/**
 * https://apis.map.qq.com/ws/geocoder/v1/
 * ?location=${encodeURIComponent(this.latitude)},${encodeURIComponent(this.longitude)}
 * &key=E7XBZ-FUXC7-D22XZ-POFT7-OD5LJ-6RBAV&get_poi=1
 */
